package org.gongliang.jfinal.common.base;

import java.util.List;

import org.gongliang.jfinal.utils.CountSqlParser;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.cache.ICache;

/*
 * model添加分页功能
 */
public abstract class ModelExt<M extends Model<M>> extends Model<M> {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("rawtypes")
	public Page<M> paginateMysql(int pageNumber, int pageSize, String sql, Object... param) {
		CountSqlParser parser = new CountSqlParser();
		String countSql = parser.getSmartCountSql(sql);
		List result = param == null || param.length == 0 ? Db.query(countSql) : Db.query(countSql, param);
		int size = result.size();
		int totalRow = 0;
		if (size == 1)
			totalRow = Integer.parseInt(result.get(0).toString()); // totalRow =
																	// (Long)result.get(0);
		else if (size > 1)
			totalRow = result.size();
		int offset = pageSize * (pageNumber - 1);
		sql = sql + " limit " + offset + " , " + pageSize;
		List<M> list = param == null || param.length == 0 ? find(sql) : find(sql, param);
		int totalPage = totalRow / pageSize + ((totalRow % pageSize == 0) ? 0 : 1);
		return new Page<M>(list, pageNumber, pageSize, totalPage, totalRow);
	}

	public Page<M> paginateMysqlByCache(String cacheName, Object key, int pageNumber, int pageSize, String sql,
			Object... paras) {
		ICache cache = getConfig().getCache();
		Page<M> result = cache.get(cacheName, key);
		if (result == null) {
			result = paginateMysql(pageNumber, pageSize, sql, paras);
			cache.put(cacheName, key, result);
		}
		return result;
	}
}
